class SchoolsController < ApplicationController
  before_filter :set_nav_session
  before_filter :login_required, :except => [:index, :area, :show, :photos, :comments]
  
  def index
    @schools = School.find(:all, :conditions => "info_source='dizhen.1kg.org' and is_hidden!=1", :select => "id, area_id")
    @photos = Photo.find(:all, :conditions => "photos.school_id<>0 and schools.info_source='dizhen.1kg.org' and schools.is_hidden!=1", 
                               :include => 'school',
                               :limit => 10,
                               :order => "photos.created_at desc")
    @comments = SchoolComment.find(:all, :conditions => "schools.info_source='dizhen.1kg.org' and schools.is_hidden!=1",
                                         :include => 'school',
                                         :limit => 10,
                                         :order => "school_comments.created_at desc")
  end
  
  def photos
    @photos = Photo.paginate(:page => params[:page] || 1,
                             :per_page => 20,
                             :conditions => "photos.school_id<>0 and schools.info_source='dizhen.1kg.org'", 
                             :include => 'school',
                             :order => "photos.created_at desc")
  end
  
  def comments
    @comments = SchoolComment.paginate(:page => params[:page] || 1,
                                       :per_page => 20,
                                       :conditions => "schools.info_source='dizhen.1kg.org'",
                                       :include => 'school',
                                       :order => "school_comments.created_at desc")
  end
  
  def area
    #@schools = School.find(:all, :conditions => ["area_id=? and info_source='dizhen.1kg.org'", params[:id]],
    #                             :include => [:photos, :comments])
    @schools = School.find_by_sql("select schools.id, schools.title, schools.updated_at, count(photos.id) as photo_count, " +
                                          "count(school_comments.id) as comment_count " + 
                                  "from schools " + 
                                  "left join photos on schools.id=photos.school_id " + 
                                  "left join school_comments on schools.id=school_comments.school_id " + 
                                  "where area_id=#{params[:id]} and info_source='dizhen.1kg.org' and is_hidden!=1 " + 
                                  "group by schools.id;")
  end
  
  def new
    @school = School.new(:area_id => params[:area])
  end
  
  def new_camp
    @school = School.new(:edu_type => 3) # 临时安置点
  end
  
  def create
    @school = School.new(params[:school])
    @school.submitor = current_user
    @school.tag_list = new_tag_list(@school)
    
    @school.info_source = "dizhen.1kg.org"
    @school.is_meta = false
    
    @school.save!
    flash[:notice] = "谢谢你提交的学校信息，在多背一公斤学校管理小组认证之前你还可以进行编辑"
    redirect_back_or_default(school_path(@school))
  rescue ActiveRecord::RecordInvalid
    render :action => "new"
  end

  def edit
    @school = School.find(params[:id])
    @school.editable_by?(self.current_user) || access_denied
  end
  
  def update
    @school = School.find(params[:id])
    @school.editable_by?(self.current_user) || access_denied
    @school.tag_list = new_tag_list(params[:school])
    
    # 完善学校资料
    if @school.is_meta?
      @school.is_meta = false
      @school.submitor = current_user
    end
    
    @school.update_attributes!(params[:school])
    flash[:notice] = "你刚刚编辑了#{@school.title}的资料"
    redirect_back_or_default(school_path(@school))
  rescue ActiveRecord::RecordInvalid
    render :action => "edit"
  end
  
  def destroy
    @school = School.find(params[:id])
    @school.update_attributes!(:is_hidden => true)
    flash[:notice] = "您将 #{@school.title} 移到了回收站"
    redirect_back_or_default(schools_path)
  end

  def show
    @school = School.find(params[:id], :conditions => {:is_hidden => false})
    @photos = @school.photos.find(:all, :order => "created_at desc")
    #@travelers = @school.travelers.find(:all, :order => "visit_at desc")
    @students = @school.students
    @comments = @school.comments
    @comment = SchoolComment.new
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "没有找到你查找的学校"
    redirect_to schools_path
  end
  
  # PUT /schools/:id;validate 
  def validate
    @school = School.find(params[:id])
    @school.update_attributes!(:is_validate => !@school.is_validate)
    if @school.is_validate
      flash[:notice] = "#{@school.title} 已通过验证"
    else
      flash[:notice] = "#{@school.title} 已取消验证"
    end
    redirect_back_or_default(school_path(@school))
  rescue ActiveRecord::RecordInvalid
    render :action => "show"
  end

  # PUT /schools/:id;visit
  def visit
    @school = School.find(params[:id])
    if @visited = Visited.find(:first, :conditions => {:school_id => @school.id, :user_id => current_user.id})
      @visited.update_attributes!(params[:visited])
    else
      @visited = Visited.new(params[:visited])
      @visited.traveler = current_user
      @visited.school = @school
      @visited.save!
    end
    redirect_back_or_default(school_path(@school.id))
  end
  
  # only for imgrate school data
    def build_tag_list
      @schools = School.find :all
      @schools.each do |s|
        s.tag_list = new_tag_list(s)
        s.save(false)
      end
      flash[:notice] = "Build tag list successfully"
    end
      
  private
  def set_nav_session
    session[:nav] = "schools"
  end
  
  def new_tag_list(school)
    new_tag_list = ""
    %w(books_need stationaries_need sports_need clothes_need accessories_need others_need classes_need teachers_need).each do |attr|
      new_tag_list += school[attr.to_sym] unless school[attr.to_sym].nil?
    end
    new_tag_list
  end
  
  def get_school_requirements(count=50)
    @tags = School.tag_counts.sort{|a,b| b.count <=> a.count}.slice(0,count).sort_by{rand}
  end
end